package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @aothor LentDent1
 * @vision 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    // 微信接口服务地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 实现微信登录功能
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        // 获取用户的openid
        String openid = getOpenid(userLoginDTO);

        // 判断openid是否为空
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断是否是新用户
        User user = userMapper.getByOpenId(openid);

        if (user == null) {
            // 新用户 完成自动注册
            user =
            User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 将新用户传入数据库
            userMapper.insert (user) ;
        }

        // 获取到openid之后 封装我们的user传给controller层
        return user;
    }
    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param userLoginDTO
     * @return
     */
    public String getOpenid (UserLoginDTO userLoginDTO) {
        // 获取code 传给微信接口返回一个openid唯一标识
        String code = userLoginDTO.getCode();
        // 调用HTTPClient请求 返回一个JSON
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        // 通过这个json获取我们需要的openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
